<template>
	<view class="order">
		<view @click="address.chooseAdress" class="address">
			<image class="address-icon" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-09.png"
				mode=""></image>
			<view v-if="address.detail.name" class="address-info">
				<view class="l">
					<view class="l1 xjs-line-two">
						{{address.detail.province}}{{address.detail.city}}{{address.detail.area}}{{address.detail.locationAddress}}{{ address.detail.address }}
					</view>
					<view class="l2">{{ address.detail.name }} {{ address.detail.mobile }}</view>
				</view>
				<uni-icons color="#808080" type="right" size="26"></uni-icons>
			</view>
			<view v-else class="address-empty">您还为添加地址，请点击添加</view>
		</view>

		<view v-for="(v, i) in product.list" class="goodInfo">
			<view class="title">
				<image class="img" :src="v.brandsLogo" mode=""></image>
				<view class="name">{{v.brandsName}}</view>
			</view>
			<view class="info">
				<scroll-view class="l" scroll-x="true">
					<view class="l-item" v-for="(item, index) in v.shopData" @click="product.open(v.shopData)">
						<view class="l-contain">
							<view class="item-img-box">
								<image class="item-img" :src="item.thumPic" mode=""></image>
								<template v-if="v.shopData.length!==1">
									<view class="amount">x{{item.amount}}</view>
									<view v-if="item.openStatus3" class="tip1 biaoqian">{{ item.openStatus3 }}</view>
								</template>
							</view>
							<view v-if="v.shopData.length==1" class="r">
								<view class="r1 xjs-line-one"><span v-if="item.openStatus3"
										class="tip1">{{ item.openStatus3 }}</span>{{ item.name }}</view>
								<view class="r2 xjs-line-one">
									<text v-if="item.skuProperties" class="m-r-10"
										v-for="(j, k) in JSON.parse(item.skuProperties)">{{ j.value }}<text
											class="m-l-10 m-r-10"
											v-if="(JSON.parse(item.skuProperties).length - 1) != k"> ; </text></text>
								</view>
								<!-- <view class="r3">
									<span class="tip2">不支持退换货</span>
								</view> -->
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="num">
					<view class="n1">¥{{Number(v.price)}}</view>
					<view class="n2">共{{v.allAmount}}件</view>
				</view>
			</view>
			<view class="good">
				<view class="l">运费</view>
				<view class="r xjs-weight-bold"><span class="tip3">￥{{Number(v.originalFreightTeam)}}</span><span>￥{{Number(v.freightPrice)}}</span>
				</view>
			</view>
			<view class="good">
				<view class="l">发货</view>
				<view class="r">{{ deliveryDate(v.shopData[0] || {},'') }}</view>
			</view>
			<view class="good">
				<view class="l">备注</view>
				<view @click="remarkFun.open(i)" class="r">
					<!-- <input placeholder="请输入备注" /> -->
					{{v.shopremarks || "请输入备注"}}
				</view>
			</view>
		</view>

		<view class="price">
			<view class="p">
				<view class="l">商品总额</view>
				<view class="r xjs-weight-bold">¥{{product.list[0].all_price}}</view>
			</view>
			<view class="p">
				<view class="l">总运费</view>
				<view class="r xjs-weight-bold"><span
						class="tip3">￥{{Number(product.list[0].all_originalFreight)}}</span>¥{{Number(product.list[0].all_freightprice)}}
				</view>
			</view>
			<view class="line"></view>
			<view class="p">
				<view class="l">合计</view>
				<view class="r allprice xjs-weight-bold">¥ {{Number(product.list[0].pay_price)}}</view>
			</view>
		</view>

		<view class="fix-btn">
			<view class="center">
				<view class="l"><span>合计：</span><span class="l-f-price xjs-weight-bold">￥{{Number(product.list[0].pay_price)}}</span></view>
				<view @click="submit.pay()" class="r xjs-btn-primary">提交订单</view>
			</view>
		</view>
	</view>
	<!-- 限制 -->
	<uni-popup ref="limitProductShowRef" type="bottom" background-color="#fff" border-radius="32rpx 32rpx 0 0">
		<limitProductItem ref="limitProductItemRef" :title="submit.title" :limitProduct="submit.limitProduct"
			:productList="product.list" :limitType="submit.limitType" @limitClose="submit.limitclose">
		</limitProductItem>
	</uni-popup>
	<!-- 备注 -->
	<uni-popup ref="remarkRef" type="bottom" background-color="#fff" border-radius="32rpx 32rpx 0 0">
		<view class="remark-content">
			<view class="deal">
				<view @click="remarkFun.close()" class="l">取消</view>
				<view @click="remarkFun.dialogInputConfirm" class="r">确定</view>
			</view>
			<view class="title">备注</view>
			<textarea class="textarea" placeholder="请输入备注" v-model="remarkFun.remarks" :maxlength="50"></textarea>
			<view class="word">{{remarkFun.remarks.length}}/50字</view>
		</view>
	</uni-popup>
	<!-- 支付 -->
	<paymentPopup ref="paymentPopupRef" @cancel="paymentFun.payFail" @confirm="paymentFun.paySuccess"
		@fail="paymentFun.payFail"></paymentPopup>
	<!-- 支付 -->
</template>
<script lang="ts" setup>
	import api from "@/api";
	import limitProductItem from "./components/limitProduct.vue";
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { ref, reactive, onMounted } from 'vue';
	import { useCartStoreToRefs,useCartStore } from "@/store/useCartStore";
	const { brandOrderList } = useCartStoreToRefs();
	const {delectPro} = useCartStore()
	import { useOrderStoreToRefs } from "@/store/useOrderStore"
	const { addressInfo } = useOrderStoreToRefs()
	import { useUserStoreToRefs } from '@/store/useUserStore';
	const { userInfo } = useUserStoreToRefs();
	const deliveryWay = ref(0);
	//-- 支付
	const paymentPopupRef = ref()
	const paymentFun = reactive({
		paySuccess: () => {
			uni.redirectTo({
				url: '/pages/shopping/orderList/index'
			})
		},
		payFail: () => {
			uni.redirectTo({
				url: '/pages/shopping/orderList/index'
			})
		},
		submit: (orderId) => {
			paymentPopupRef.value.open({
				orderId: orderId,
				payAmount: product.list[0].pay_price,
				payBusinessType: 3,
				checkOrderType: "shopping"
			});
		}
	})
	onLoad((params) => {
		product.isFrom = params.isFrom || ''
	})
	// -- 支付
	onShow(() => {
		console.log(brandOrderList)
		console.log(addressInfo.value)
		address.detail = addressInfo.value
		product.getList()
	})
	const remarkRef = ref()
	const remarkFun = reactive<any>({
		key: 0,
		remarks: "",
		close: () => {
			remarkRef.value.close()
		},
		open: (i) => {
			remarkFun.remarks = product.list[i].shopremarks || ""
			remarkFun.key = i
			remarkRef.value.open()
		},
		dialogInputConfirm: (e) => {
			console.log(remarkFun.remarks)
			product.list[remarkFun.key].shopremarks = remarkFun.remarks
			remarkFun.close()
		}
	})
	const limitProductShowRef = ref()
	const limitProductItemRef = ref(null)
	const submit = reactive<any>({
		limitProduct: [],
		limitType: 1,
		title: "",
		limitclose: (num) => {
			console.log(num)
			limitProductShowRef.value.close();
			//此时表示继续下单，这种情况下下单时不在走校验的流程
			if (num == 4) {
				submit.pay(4)
			}
			if (num == 2) {
				uni.navigateBack({
					delta: 1
				});
			}
			if (num == 3) {
				let arr = product.initProduct
				let otherArr = [];
				arr.forEach((item) => {
					let status = submit.limitProduct.find((citem) => {
						if (item.skuCode == citem.skuCode) {
							return true;
						}
					});
					if (!status) {
						otherArr.push(item);
					}
				});
				console.log("otherArr", otherArr)
				product.getList(otherArr)
			}
		},
		check: () => {
			return new Promise(async (resolve, reject) => {
				//第一步验证 - 多规格商品提交检查提示
				let proParams1 = {};
				proParams1 = await getOrderNumber(product.list);
				const verifyRes1 : any = await api({
					method: "POST",
					url: `/mall/order/V2021/submitOrderCheck`,
					data: proParams1
				});
				console.log(verifyRes1)
				if (verifyRes1.data.length > 0) {
					submit.limitProduct = await handleList(verifyRes1.data);
					limitProductShowRef.value.open();
					setTimeout(() => {
						limitProductItemRef.value && limitProductItemRef.value.getList()
					}, 300)
					submit.limitType = 1
					let productAccont = submit.limitProduct.reduce((pre, cur) => {
						return pre + Number(cur.amount);
					}, 0);
					submit.title = "抱歉，以下商品（" + productAccont + "件）无法下单购买";
					console.log()
					resolve(false)
					return;
				}
				//第二步验证 - 需修改数量的商品
				let skuCodes = [],
					counts = [];
				const goodsList = product.list.reduce((list, item) => {
					list = list.concat(item.shopData || []);
					return list;
				}, []);
				// 商品去重
				const uniqueList = mergeGoods(
					goodsList,
					(single, repeat) => {
						if (single.skuCode == repeat.skuCode) {
							single.amount += Number(repeat.amount);
							return true;
						}
					},
					"skuCode"
				);
				uniqueList.forEach((itemChild) => {
					skuCodes.push(itemChild.skuCode);
					counts.push(itemChild.amount);
				});
				let proParams2 : any = {};
				proParams2.skuCodes = skuCodes.join();
				proParams2.counts = counts.join();
				const verifyRes2 : any = await api({
					method: "get",
					url: `/mall/goods/V2021/v2/purchaseCheck/buyCount`,
					data: proParams2,
				});
				console.log(verifyRes2, proParams2)
				if (verifyRes2.data.length > 0) {
					submit.limitProduct = await handleList(verifyRes2.data);
					limitProductShowRef.value.open();
					submit.limitType = 2;
					let productAccont = submit.limitProduct.reduce((pre, cur) => {
						return pre + Number(cur.amount);
					}, 0);
					submit.title = `请调整商品的购买数量(共${productAccont}件)`;
					resolve(false)
					return;
				}
				//第三步验证 - 提示需注意的商品-农场商品不做拦截
				proParams2.addressId = address.detail.id;
				proParams2.deliveryWay = deliveryWay.value;
				const verifyRes3 : any = await api({
					method: "get",
					url: `/mall/goods/V2021/v2/purchaseCheck/stocksAndLogistics`,
					data: proParams2,
				});
				if (verifyRes3.data.length > 0) {
					submit.limitProduct = await handleList(verifyRes3.data);
					limitProductShowRef.value.open();
					submit.limitType = 3;
					submit.title = "请注意以下商品情况，是否继续下单？";
					resolve(false)
					return;
				}
				resolve(true)
			})
		},
		pay: async (num) => {
			
			uni.showLoading({
				mask:true,
				title:'加载中'
			})
			if (!address.detail.name) {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: '请先选择地址'
				})
				return
			}
			if (num != 4) {
				let checkResult = await submit.check()
				if (!checkResult) {
					uni.hideLoading()
					return;
				}
			}
			// 商品类型-判断第一条数据
			const goodstype = product.list[0].shopData[0].saleChannel;
			let params : any = await getOrderNumber(product.list);
			params.orders.origin = 1
			params.orders.receiverLocationAddress = address.detail.locationAddress
			//生成订单号
			if (goodstype == 0) {
				let res : any = await api({
					method: "post",
					url: `/mall/order/V2021/v3/submit`,
					data: params,
				});
				if (res.code != 0) {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					uni.hideLoading()
					return
				}
				delectPro()
				//-- 支付
				paymentFun.submit(res.data)
				// -- 支付
			}else{
				uni.hideLoading()
			}
		}
	})
	const product = reactive({
		isFrom: "",
		list: [],//处理后渲染的商品
		initProduct: [],//初始商品
		open: (item) => {
			submit.limitProduct = item
			limitProductShowRef.value.open();
			setTimeout(() => {
				limitProductItemRef.value && limitProductItemRef.value.getList()
			}, 300)
			submit.limitType = 4
			let productAccont = submit.limitProduct.reduce((pre, cur) => {
				return pre + Number(cur.amount);
			}, 0);
			submit.title = "商品清单（" + productAccont + "件）";
			console.log()
		},
		getList: async (list ?) => {
			console.log("brandOrderList.value", brandOrderList.value)
			if (list) {
				product.initProduct = list
			} else {
				// product.initProduct = []
				// let cartRes : any = await api({
				// 	method: "get",
				// 	url: `/mall/shopping/goods/v2/car`,
				// });
				// product.initProduct = cartRes.data
				product.initProduct = brandOrderList.value
				console.log("initProduct", product.initProduct)
			}

			//处理组数数据
			let arr = []
			var brandsRefereeList = [];
			product.initProduct.forEach(item => {
				let dateParams;
				if (item.addTime) {
					item.addTime = item.addTime.replace(/\-/g, '/')
					dateParams = new Date(item.addTime);

				} else {
					dateParams = new Date();
				}
				let dateTime = dateParams.setHours(dateParams.getHours() + 8);
				let dataTimeIos = new Date(dateTime).toISOString();
				dataTimeIos = dataTimeIos.substr(0, dataTimeIos.length - 1);
				arr.push({
					addTime: dataTimeIos,
					amount: item.amount,
					id: item.id,
					isSelect: 1,
					refereeId: "",
					skuCode: item.skuCode,
					storeId: item.storeId
				})
			})
			//处理后请求shopping-car接口获取最新最全的数据
			//处理从购物车列表获取的数据
			let result : any = await api({
				method: "PUT",
				url: `/mall/shopping/goods/V2021/v3/shopping-car`,
				data: JSON.stringify(arr),
			});
			console.log("result", result.data);
			let params = result.data.reduce((pre, cur) => {
				return pre.concat(cur.shoppingCarVOlist);
			}, []);
			console.log("params", params);
			let productArr = []
			params.forEach((item, index) => {
				productArr[index] = {
					goodsId: item.id,
					name: item.name ? item.name : item.goodsName,
					price: item.price,
					count: item.amount,
					weight: item.weight,
					deliverWeight: item.deliverWeight,
					packageBoxWeight: item.packageBoxWeight,
					ifDeliverAlone: item.ifDeliverAlone,
					packageLimit: item.packageLimit,
					ifInsurance: item.ifInsurance,
					specifyExpress: item.specifyExpress,
					expressFeeTemplateId: item.logisticsTemplateId,
					brandsId: item.brandsId,
					deliverVolume: item.deliverVolume,
					skuCode: item.skuCode,
					isLettering: (item.isLettering == 1 && item.letteringMsg) ? 1 : 0,
					presellOn: item.saleType == 3 ||
						(item.stocks == 0 && item.saleType == 2) ||
						(item.stocks == 0 && item.prepareStocks > 0) ?
						1 :
						0, //1 预售  0 非预售

				}
			})
			console.log("productArr", productArr)
			const paramsFreight = {};
			const deliveryWay = params[0].deliveryWay || 0;
			paramsFreight["productArr"] = encodeURIComponent(
				JSON.stringify(productArr)
			);
			console.log("paramsFreight", paramsFreight)
			let sequentialOrderList : any = await api({
				method: "post",
				url: `/mall/order/V2021/getSplitOrders`,
				data: {
					...paramsFreight,
					deliveryWay,
				},
			})
			sequentialOrderList = sequentialOrderList.data || [];
			// 将拆分的订单数据添加状态标识——商品中有现货和预售混合时，将两者分开
			sequentialOrderList.forEach((item, index) => {
				item.orderGoodsDTOS.forEach((goodItem, goodIndex) => {
					item.orderGoodsDTOS[goodIndex] = productStatus(goodItem);
				});
			});
			console.log("sequentialOrderList", sequentialOrderList)
			// 计算运费
			let arrFrei = []
			let res2 : any = ""
			if (address.detail.id) {
				paramsFreight["addressId"] = address.detail.id;
				// 获取运费
				res2 = await api({
					method: "POST",
					url: `/mall/order/V2021/v2/freight`,
					data: {
						...paramsFreight,
						deliveryWay,
					},
				});
				console.log("res2", res2)
				res2 = res2.data;

				res2.forEach((item) => {
					item.skuList.forEach((citem, i) => {
						let chi = JSON.parse(JSON.stringify(item));
						chi.skuCode = citem;
						if (i > 0) {
							chi.freights = "0.00";
							chi.originalFreight = "0.00";
						}
						arrFrei.push(chi);
					});
				});
			}
			if (arrFrei.length > 0) {
				params.forEach((item) => {
					arrFrei.forEach((citem) => {
						if (
							item.brandsId == citem.brandsId &&
							item.skuCode == citem.skuCode
						) {
							item.freights = citem.freights;
							item.originalFreight = citem.originalFreight;
						}
					});
				});
			}
			console.log("paramsparams", params)
			let brandsList = [];
			let len = params.length;
			// 拆分开始
			sequentialOrderList.forEach((item) => {
				item.orderGoodsDTOS.forEach((orderGoodsItem, orderGoodsIndex) => {
					const goodInfo =
						params.find((goodItem) => {
							return goodItem.skuCode == orderGoodsItem.skuCode;
						}) || {};

					// 合并对象，相同属性合并时，值为空则不覆盖
					function mergeRules(objValue, srcValue) {
						return objValue == null ? srcValue : objValue;
					}
					var mergeObejct = customPartialRight(
						customAssignInWith,
						mergeRules
					);

					item.orderGoodsDTOS[orderGoodsIndex] = mergeObejct(
						orderGoodsItem,
						goodInfo
					);
					item.orderGoodsDTOS[orderGoodsIndex].amount =
						orderGoodsItem.count;
				});
				item.shopData = item.orderGoodsDTOS;
			});
			// 拆分结束

			// 配备模板渲染所需要的数据
			sequentialOrderList[0] = {
				...sequentialOrderList[0],
				...((sequentialOrderList[0] &&
					sequentialOrderList[0].orderGoodsDTOS &&
					sequentialOrderList[0].orderGoodsDTOS[0]) || {}),
			};
			brandsList = sequentialOrderList;

			brandsList[0].all_price = 0;
			brandsList[0].all_freightprice = 0;
			brandsList[0].all_subtotalPrice = 0;
			brandsList[0].all_originalFreight = 0;
			// 匹配运费 , 总额  小计等
			brandsList.forEach((citem, i) => {
				// 运费
				citem.freightPrice = citem.shopData.reduce((pre, cur) => {
					return pre + Number(cur.freights || 0);
				}, 0);
				citem.freightPrice = citem.freightPrice.toFixed(2);
				//原运费
				citem.originalFreightTeam = citem.shopData.reduce((pre, cur) => {
					return pre + Number(cur.originalFreight || 0);
				}, 0);
				citem.originalFreightTeam = citem.originalFreightTeam.toFixed(2);
				// 品牌下的商品总额
				citem.price = citem.shopData.reduce((pre, cur) => {
					return pre + Number(cur.amount) * Number(cur.price);
				}, 0);
				citem.allAmount = citem.shopData.reduce((pre, cur) => {
					return pre + Number(cur.amount)
				}, 0);
				citem.price = citem.price.toFixed(2);
				//品牌下的商品小计
				citem.subtotalPrice =
					Number(citem.price) +
					Number(!citem.freightPrice ? 0 : citem.freightPrice);
				citem.subtotalPrice = citem.subtotalPrice.toFixed(2);

				// 所有商品总费用
				brandsList[0].all_price += Number(brandsList[i].price);
				// 所有商品总运费
				// brandsList[0].all_freightprice += Number(brandsList[i].freightPrice ==
				// 	undefined ? 0 : brandsList[i].freightPrice)
				// 所有商品原始总运费
				// brandsList[0].all_originalFreight += Number(brandsList[i].originalFreightTeam ==undefined ? 0 : brandsList[i].originalFreightTeam)
			});
			//所有商品总运费
			if (address.detail.name && params[0].saleChannel != 4) {
				res2.forEach((item) => {
					brandsList[0].all_freightprice += Number(item.freights);
					// 所有商品原始总运费
					brandsList[0].all_originalFreight += Number(
						item.originalFreight || 0
					);
				});
			}
			brandsList[0].brandsRefereeList = brandsRefereeList;
			brandsList[0].all_freightprice =
				brandsList[0].all_freightprice.toFixed(2);
			// 所有商品总计
			brandsList[0].all_subtotalPrice = (
				Number(brandsList[0].all_price) +
				Number(brandsList[0].all_freightprice)
			).toFixed(2);

			brandsList[0].all_price = brandsList[0].all_price.toFixed(2);
			brandsList[0].all_originalFreight = brandsList[0].all_originalFreight.toFixed(2);

			brandsList[0].pay_price = Number(brandsList[0].all_price) + Number(brandsList[0].all_freightprice)
			product.list = brandsList
			console.log(brandsList)
		}
	})
	const address = reactive<any>({
		detail: {},
		chooseAdress: () => {
			uni.navigateTo({
				url: "/pages/addressManagement/addressList/index?select=true"
			});
		}
	})
	// 从商品列表中筛出符合list的指定商品
	const handleList = async (list) => {
		return new Promise((resolve, reject) => {
			let arr = [];
			let arr2 = product.list.reduce((pre, cur) => {
				return pre.concat(cur.shopData);
			}, []);
			// 商品去重
			arr2 = mergeGoods(
				arr2,
				(single, repeat) => {
					if (single.skuCode == repeat.skuCode) {
						single.amount += Number(repeat.amount);
						return true;
					}
				},
				"skuCode"
			);
			arr2.forEach((item) => {
				list.forEach((citem) => {
					if (item.skuCode == citem.skuCode) {
						item.tipList = citem.tipList;
						arr.push(item);
					}
				});
			});
			resolve(arr);
		});
	}
	//农场商品普通商品、门店商品生成订单号所需参数
	const getOrderNumber = async (brandOrderList) => {
		return new Promise((resolve, reject) => {
			// 生成orders????
			let orders : any = {};

			//生成提交的商品信息
			let orderGoods = [];

			// 商品类型
			const goodstype = brandOrderList[0].shopData[0].saleChannel;

			orders["buyerId"] = userInfo.value.id; //买家ID

			// 门店商品不用快递
			if (brandOrderList[0].shopData[0].saleChannel != 4) {
				// 收件信息
				orders["receiverName"] = address.detail.name; //收件人姓名
				orders["receiverMobile"] = address.detail.mobile; //手机人手机号
				if (address.detail.isInternal != 1) {
					orders["receiverProvince"] = address.detail.userAddress ? address.detail.userAddress.province : address.detail.province; //收件省
					orders["receiverCity"] = address.detail.userAddress ? address.detail.userAddress.city : address.detail.city; //收件市
					orders["receiverArea"] = address.detail.area; //收件区
				} else {
					orders["receiverProvince"] = address.detail.country;
					orders["receiverCity"] = "";
					orders["receiverArea"] = "";
				}
				orders["receiverAddress"] = address.detail.address; //收件人地址
				orders["receiverPostcode"] = address.detail.postcode; //收件邮政编码
			}
			orders["goodsMoney"] = brandOrderList[0].all_price; //商品金额
			orders["expressFee"] = brandOrderList[0].all_freightprice; //运费
			// orders['totalMoney'] = brandOrderList[0].all_subtotalPrice; //总金额
			orders["totalMoney"] = brandOrderList[0].pay_price; //总金额
			// 因为之前农场和普通商品供用product字段，现在普通商品使用product、农场使用farm分开需要更换判断方式
			// orders['buyType'] = this.productType = 'product' ? 1 : 2;
			// orders['useScores'] = this.productType = 'product' ? 0 : Number(brandOrderList[0].all_price);
			orders["buyType"] = 1; //购买类型：1-现金购买
			orders["useScores"] = 0; //	使用积分（buy_type为2或3时）
			orders["reduceMoney"] = "0.00"; //优惠金额
			orders["promotionList"] = ""; //促销优惠活动id列表，逗号分隔：空-无促销优惠
			orders["invoiceType"] = 0; //发票类型
			orders["useFCardGoodsListJson"] = "";
			orders["useFoundationCardList"] = "";
			orders["deliveryWay"] = deliveryWay.value; // 暂不发货
			orders["addressId"] = address.detail.isInternal == 1 ? address.detail.id : "";

			//生成备注
			let remarks = [
				{
					presellOn: 1,
					remark: {}
				},
				{
					presellOn: 0,
					remark: {}
				},
				{
					isLettering: 1,
					remark: {}
				}
			];

			//区分备注格式
			brandOrderList.forEach((item) => {
				item.shopData.forEach((itemChild) => {
					if (itemChild.isLettering && itemChild.letteringMsg) {
						remarks[2].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
					} else if (
						itemChild.saleType == 3 ||
						(itemChild.stocks == 0 && itemChild.saleType == 2) ||
						(itemChild.stocks == 0 && itemChild.prepareStocks > 0)
					) {
						remarks[0].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
					} else {
						remarks[1].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
					}

					if (goodstype == 0 && !(brandOrderList[0].oneBuyPromotionVO && brandOrderList[0].oneBuyPromotionVO.id)) {
						orders["remark"] = JSON.stringify(remarks);
					}
					if (goodstype == 0 && brandOrderList[0].oneBuyPromotionVO && brandOrderList[0].oneBuyPromotionVO.id) {
						orders["remark"] = brandOrderList[0].shopremarks || "";
					}
					if (goodstype == 2) {
						orders["remark"] = brandOrderList[0].shopremarks || "";
					}

					let iObj : any = {
						goodsId: itemChild.id, //产品ID
						name: itemChild.name ? itemChild.name : itemChild.goodsName, //商品名称
						price: itemChild.price, //市场价格
						count: itemChild.amount, //数量
						thumPic: itemChild.thumPic, //缩略图
						deliverVolume: itemChild.deliverVolume, // 体积
						deliverWeight: itemChild.deliverWeight, //发货重量（连包装的重量，g）
						packageBoxWeight: itemChild.packageBoxWeight, //发货（单个）箱子重量（g）
						weight: itemChild.weight,
						skuCode: itemChild.skuCode,
						isLettering: Boolean(itemChild.isLettering && itemChild.letteringMsg) ? 1 : 0,
						letteringMsg: itemChild.letteringMsg,
						deliveryType: itemChild.deliveryType // 发货方式
					};
					if (itemChild.setMealInfoVO) {
						const setMealInfoVO = itemChild.setMealInfoVO || {};
						const setMealSkuList = setMealInfoVO.setMealSkuList || [];
						const goodsInfo =
							setMealSkuList.find((mealSkuItem) => {
								return itemChild.skuCode == mealSkuItem.skuCode;
							}) || {};
						iObj.price = goodsInfo.currentPrice;
					}
					// #ifdef APP-PLUS
					iObj.orderSourceType = 2;
					// #endif
					// #ifdef MP-WEIXIN
					iObj.orderSourceType = 1;
					// #endif
					if (uni.getSystemInfoSync().platform == "ios") {
						iObj.phoneType = 2;
					} else if (uni.getSystemInfoSync().platform == "android") {
						iObj.phoneType = 1;
					} else {
						iObj.phoneType = 0;
					}
					orderGoods.push(iObj);
				});
			});
			// 商品去重
			// orderGoods = mergeGoods(
			// 	orderGoods,
			// 	(single, repeat) => {
			// 		if (single.skuCode == repeat.skuCode) {
			// 			single.count += Number(repeat.count);
			// 			return true;
			// 		}
			// 	},
			// 	"skuCode"
			// );

			// #ifdef APP-PLUS
			orders.orderSourceType = 2;
			// #endif
			// #ifdef MP-WEIXIN
			orders.orderSourceType = 1;
			// #endif
			if (uni.getSystemInfoSync().platform == "ios") {
				orders.phoneType = 2;
			} else if (uni.getSystemInfoSync().platform == "android") {
				orders.phoneType = 1;
			} else {
				orders.phoneType = 0;
			}
			resolve({
				orders: orders,
				orderGoods: orderGoods,
				promoterId: userInfo.value.rebrandId, // 假设user在userInfo里，需根据实际情况调整
				sourceType: userInfo.value.refereeType, // 假设user在userInfo里，需根据实际情况调整
				brandsRefereeList: brandOrderList[0].brandsRefereeList
			});
		});
	}
	const productStatus = (itemChild) => {
		//判断预售时间是否到期
		if (itemChild.status == 0 && itemChild.saleTime) {
			let curTime = new Date().getTime();
			itemChild.saleTime = itemChild.saleTime.replace(/\-/g, "/");
			let endTime = new Date(itemChild.saleTime).getTime();
			if (endTime <= curTime) {
				itemChild.status = null;
			}
		}

		if (itemChild.oneBuyPromotionVO) {
			const infoData = itemChild.oneBuyPromotionVO;
			let startTimestamp = timeStamp(infoData.startTime); //活动开始时间戳
			let endTimestamp = timeStamp(infoData.endTime); //活动结束时间戳
			let nowTimestamp = new Date().getTime(); //获取当前时间戳
			if (
				infoData.status == 0 ||
				(infoData.status == 1 && nowTimestamp < startTimestamp)
			) {
				// 一元购活动未开始
				itemChild.openStatus1 = "未开始";
				itemChild.openColor1 = "#F29582";
			}
			if (
				infoData.status == 1 &&
				nowTimestamp >= startTimestamp &&
				nowTimestamp <= endTimestamp
			) {
				// 一元购活动在有效期
				itemChild.openStatus1 = "抢购中";
				itemChild.openColor1 = "#DD1624";
			}
			if (
				infoData.status == 2 ||
				(infoData.status == 1 && nowTimestamp > endTimestamp)
			) {
				// 一元购活动已结束
				itemChild.openStatus1 = "已结束";
				itemChild.openColor1 = "#999";
			}
		}
		// if (itemChild.oneBuyPromotionVO) {
		// 	itemChild.openStatus1 = "抢购中"
		// 	itemChild.openColor1 = "#DD1624"
		// }

		if (itemChild.status == 0) {
			itemChild.openStatus2 = "即将开售";
			itemChild.openColor2 = "#FF4C4E";
			itemChild.isPredict = true; //外部处理倒计时
			itemChild.disabled = true;
		}
		if (
			itemChild.saleType == 3 ||
			(itemChild.stocks == 0 && itemChild.saleType == 2) ||
			(itemChild.stocks == 0 && itemChild.prepareStocks > 0) ||
			itemChild.presellOn == 1
		) {
			itemChild.openStatus3 = "预售";
			itemChild.openColor3 = "#FF4C4E";
			const presalesDelivery = getPresalesDelivery(itemChild);
			itemChild.isPredict =
				itemChild.deliveryTimeType == 0 ?
					presalesDelivery :
					`${itemChild.deliveryMsg}`;
		}
		//运营在后台删除了商品
		if (itemChild.delFlag == 1) {
			itemChild.invalidIntro = "规格不存在";
			return itemChild;
		}
		//商品下架
		if (itemChild.status == 2) {
			itemChild.invalidIntro = "商品已下架";
			return itemChild;
		}
		// 售卖完毕
		if (itemChild.stocks == 0 && itemChild.prepareStocks == 0) {
			itemChild.invalidStatus = false;
			itemChild.sellOut = true;
			itemChild.disabled = true;
			itemChild.invalidIntro = "商品已抢光";
			return itemChild;
		}
		//规格禁用
		if (itemChild.skuStatus == 0 || itemChild.skuDelFlag == 1) {
			itemChild.invalidIntro = "规格不存在";
			return itemChild;
		}
		if (itemChild.oneBuyPromotionVO) {
			itemChild.invalidIntro = "价格已失效";
			return itemChild;
		}
		// 为1时表示刻字
		if (itemChild.isLettering == 1) { }
		//是否已达购买数量
		if (getLimitStatus(itemChild)) {
			itemChild.isError2 = true;
			itemChild.errorMessag =
				getLimitTime(
					itemChild.purchaseLimitType,
					itemChild.purchaseLimitRules,
					1
				) +
				(itemChild.alreadyBuyNum ?
					`(已购${itemChild.alreadyBuyNum ? itemChild.alreadyBuyNum : "0"}件)` :
					"");

			itemChild.invalidIntro = "已购数量已达限购上限";
			return itemChild;
		}

		return itemChild;
	}

	const getLimitStatus = (product) => {
		//限购数量是否超标
		if (product.purchaseLimitType == 0 || product.isLimit == 1) {
			return false;
		}

		if (product.purchaseLimitType) {
			var num =
				product.purchaseLimitType == 1 ?
					Number(product.purchaseLimitRules.split(",")[1]) :
					Number(product.purchaseLimitRules);
			var syNum =
				product.purchaseLimitType >= 1 ?
					num -
					Number(product.alreadyBuyNum == null ? 0 : product.alreadyBuyNum) :
					"";
			return product.purchaseLimitType != 0 && syNum <= 0;
		}
	}

	//purchaseLimitType 0不限购 1按时间限购 2永久限购
	const getLimitTime = (purchaseLimitType, purchaseLimitRules, type) => {
		if (purchaseLimitType != 0) {
			if (purchaseLimitType == 1) {
				var arr = purchaseLimitRules.split(",");
			}
			var num = purchaseLimitType == "1" ? arr[1] : purchaseLimitRules;
			if (purchaseLimitType == 1) {
				if (arr[0] == 7) {
					var day = "每周";
				} else if (arr[0] == 1) {
					var day = "每天";
				} else {
					var day = "每月";
				}
			} else {
				var day = ""; //永久
			}
			if (type == 1) {
				return day + "限购" + num + "件";
			}
		}
	}

	const customAssignInWith = (target, ...sources) => {
		const customizer =
			typeof sources[sources.length - 1] === "function" ?
				sources.pop() :
				undefined;

		sources.forEach((source) => {
			if (source === null || source === undefined) {
				return;
			}

			// 遍历源对象的所有可枚举属性，包括原型链上的属性
			for (let key in source) {
				if (
					Object.prototype.hasOwnProperty.call(source, key) ||
					source[key] !== undefined
				) {
					const targetValue = target[key];
					const sourceValue = source[key];

					if (customizer) {
						const result = customizer(
							targetValue,
							sourceValue,
							key,
							target,
							source
						);
						if (result !== undefined) {
							target[key] = result;
							continue;
						}
					}

					if (sourceValue !== undefined) {
						target[key] = sourceValue;
					}
				}
			}
		});

		return target;
	}

	const customPartialRight = (func, ...partials) => {
		return function (...args) {
			const newArgs = [...args, ...partials];
			return func.apply(this, newArgs);
		};
	}
	const deliveryDate = (goodInfo : any, orderInfo : any) => {
		const presalesDelivery = getPresalesDelivery(goodInfo);
		if (presalesDelivery) {
			return presalesDelivery;
		} else if (goodInfo.expressMsg) {
			return goodInfo.expressMsg;
		} else if (goodInfo.spotCustDeliveryMsg || goodInfo.spotDeliveryMsg) {
			return goodInfo.spotDeliveryTimeType == 0
				? Number(goodInfo.spotDeliveryMsg.split(",")[0].split(":")[0]).toString() +
				"点前下单当天发货，" +
				Number(goodInfo.spotDeliveryMsg.split(",")[0].split(":")[0]).toString() +
				"点后下单则次日发货" +
				(goodInfo.spotDeliveryMsg.split(",")[1] == 1 ? ",节假日顺延" : "")
				: goodInfo.spotCustDeliveryMsg;
		}
	};
	// 预售商品发货方式
	const getPresalesDelivery = (goodInfo : any) => {
		// 判断是否为预售
		const isPresell = goodInfo.saleType == 3 || (goodInfo.stocks == 0 && goodInfo.saleType == 2) || (goodInfo.stocks ==
			0 &&
			goodInfo.prepareStocks > 0) || goodInfo.presellOn == 1
		if (goodInfo && (isPresell || goodInfo.openStatus3) && goodInfo.prepareDeliveryTime) {
			let monthPart
			const prepareDeliveryTimeComponent = goodInfo.prepareDeliveryTime.split(',')
			const month = prepareDeliveryTimeComponent[0].split('-')[1]
			switch (Number(prepareDeliveryTimeComponent[2])) {
				case 1:
					monthPart = "上旬"
					break;
				case 2:
					monthPart = "中旬"
					break;
				case 3:
					monthPart = "下旬"
					break;
			}
			return `预售，${Number(month)}月${monthPart}发货`
		} else if (goodInfo && (isPresell || goodInfo.openStatus3) && goodInfo.deliveryMsg) {
			if (goodInfo.deliveryTimeType == 0) {
				let time = goodInfo.deliveryMsg.split('-')[0] + '年' + goodInfo.deliveryMsg.split('-')[1] + '月' + goodInfo
					.deliveryMsg.split('-')[2] + '日后开始发货'
				return time
			} else {
				return goodInfo.deliveryMsg
			}
		}
		return false


	}
	//时间转换成时间戳
	const timeStamp = (date) => {
		return (
			new Date(date.replace(/-/g, "/")).getTime() || new Date(date).getTime()
		);
	}
	const mergeGoods = (list, fn, sortName) => {
		list = deepClone(list);
		// 通过排序将同类项相邻排列
		list.sort((a, b) => {
			if (sortName) {
				return a[sortName] - b[sortName];
			}
			return a - b;
		});

		// 合并相邻的同类项
		list.forEach((item, index) => {
			mergecontiguousGoods(item, list, index, fn);
		});

		return list;
	}
	// 合并相邻的同类项
	const mergecontiguousGoods = (item, list, index, fn) => {
		for (let i = index + 1; i < list.length; i++) {
			if ((fn && fn(item, list[i])) || item === list[i]) {
				list.splice(i, 1);
				mergecontiguousGoods(item, list, index, fn);
			}
			break;
		}
		return item;
	}
	// 对象深拷贝
	const deepClone = (data) => {
		let type = getObjType(data);
		let obj;
		if (type === 'array') {
			obj = []
		} else if (type === 'object') {
			obj = {}
		} else {
			return data
		}
		if (type === 'array') {
			for (let i = 0, len = data.length; i < len; i++) {
				obj.push(deepClone(data[i]))
			}
		} else if (type === 'object') {
			for (let key in data) {
				obj[key] = deepClone(data[key])
			}
		}
		return obj
	}
	//  检查对象类型
	const getObjType = (obj) => {
		const map = {
			'[object Boolean]': 'boolean',
			'[object Number]': 'number',
			'[object String]': 'string',
			'[object Function]': 'function',
			'[object Array]': 'array',
			'[object Date]': 'date',
			'[object RegExp]': 'regExp',
			'[object Undefined]': 'undefined',
			'[object Null]': 'null',
			'[object Object]': 'object'
		};
		return map[Object.prototype.toString.call(obj)];
	}
</script>
<style lang="scss" scoped>
	.tip1 {
		display: inline-block;
		line-height: 1;
		border-radius: 50rpx;
		padding:4rpx 8rpx;
		border: 2rpx solid #6363FF;
		color: #6363FF;
		font-size: 24rpx;
		box-sizing: border-box;
		margin: 5rpx 6rpx 5rpx 0;
	}

	.tip2 {
		text-align: center;
		border-radius: 10rpx;
		padding: 6rpx 16rpx;
		border: 1rpx solid var(--color-primary);
		color: var(--color-primary);
		font-size: 24rpx;
		margin: 5rpx 0;
	}

	.tip3 {
		text-decoration: line-through;
		color: #7C807F;
		font-size: 30rpx;
	}

	.remark-content {
		padding: 32rpx;
		box-sizing: border-box;
		width: 750rpx;
		background-color: #fff;
		.deal {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			color: var(--color-primary);
		}

		.title {
			height: 88rpx;
			line-height: 88rpx;
			border-bottom: 1rpx solid #e4e6e6;
			font-size: 32rpx;
			font-weight: bold;
		}

		.textarea {
			padding: 32rpx 0;
			box-sizing: border-box;
			width: 100%;
			font-size: 26rpx;
			font-weight: normal;
			line-height: 1.6;
		}

		.word {
			text-align: right;
			font-size: 26rpx;
			color: #5C5E5E;
		}
	}

	.order {
		padding: 32rpx 32rpx 200rpx;
		box-sizing: border-box;

		.address {
			background-color: #fff;
			padding: 32rpx 8rpx 32rpx 32rpx;
			border-radius: 24rpx;
			display: flex;
			align-items: center;

			.address-icon {
				width: 48rpx;
				height: 48rpx;
			}

			.address-empty {
				font-size: 28rpx;
				padding: 0 32rpx;
			}

			.address-info {
				width: calc(100% - 48rpx);
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 0 0 32rpx;

				.l {
					width: 88%;

					.l1 {
						font-size: 32rpx;
					}

					.l2 {
						margin-top: 16rpx;
						font-size: 26rpx;
						color: #808080;
					}
				}
			}
		}

		.goodInfo {
			margin-top: 32rpx;
			padding: 32rpx 0 32rpx 32rpx;
			border-radius: 24rpx;
			background-color: #fff;

			.title {
				display: flex;
				align-items: center;
				padding-right:32rpx;
				.img {
					width: 40rpx;
					height: 40rpx;
					border-radius: 4rpx;
					flex-shrink: 0;
				}

				.name {
					font-size: 32rpx;
					font-weight: bold;
					padding-left: 16rpx;
				}
			}

			.info {
				padding: 48rpx 0 0;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.l {
					width: calc(100% - 128rpx);
					white-space: nowrap;

					.l-item {
						display: inline-block;
						padding-right: 16rpx;

						.l-contain {
							display: flex;

							.item-img-box {
								width: 160rpx;
								height: 160rpx;
								position: relative;
								border-radius: 24rpx;
								overflow: hidden;

								.item-img {
									width: 160rpx;
									height: 160rpx;
								}

								.amount {
									position: absolute;
									right: 0;
									bottom: 0;
									padding: 5rpx 10rpx;
									color: #fff;
									border-radius: 50% 0 0 0;
									background-color: rgba(0, 0, 0, 0.5);
									font-size: 24rpx;
								}

								.biaoqian {
									position: absolute;
									left: 24rpx;
									top: 24rpx;
								}
							}

							.r {
								width: 320rpx;
								padding-left: 16rpx;

								.r1 {
									width: 100%;
									font-size: 30rpx;
									padding: 5rpx 0 8rpx;
								}

								.r2 {
									width: 100%;
									margin-top: 6rpx;
									color: #808080;
									font-size: 24rpx;
								}

								.r3 {
									margin: 32rpx 0 10rpx;
								}
							}
						}

					}
				}

				.num {
					width: 128rpx;
					text-align: center;
					border-left: 1rpx solid #f6f6f6;
					box-sizing: border-box;
					.n1 {
						color: var(--color-primary);
						font-size: 28rpx;
						font-weight: bold;
						word-break: break-word;
					}

					.n2 {
						color: #7C807F;
						font-size: 24rpx;
						margin-top: 10rpx;
					}
				}
			}

			.good {
				margin-top: 48rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-right:32rpx;
				.l {
					color: #5C5E5E;
					font-size: 26rpx;
				}

				.r {
					width: 70%;
					font-size: 30rpx;
					text-align: right;
					word-break: break-all;
				}
			}
		}

		.price {
			margin-top: 32rpx;
			padding: 32rpx 32rpx 0;
			border-radius: 24rpx;
			background-color: #fff;

			.line {
				margin:0 0 32rpx;
				border-top: 1px solid #E6E6E6;
			}

			.p {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-bottom: 32rpx;

				.l {
					color: #5C5E5E;
					font-size: 26rpx;
				}

				.r {
					font-size: 30rpx;
				}

				.allprice {
					color: var(--color-primary)
				}
			}


		}

		.fix-btn {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			padding-bottom: var(--safe-area-bottom);
			background-color: #fff;
			z-index: 10;

			.center {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding:8rpx 32rpx 32rpx;
				box-sizing: border-box;

				.l {
					font-size: 24rpx;

					.l-f-price{
						font-size: 32rpx;
					}
				}

				.r {
					width: 256rpx;
				}
			}
		}
	}
</style>